package com.huatai.common.util;


import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {

    /**
     * 发送http请求
     * @param requestUrl
     * @return
     */
    public static Object sendOkHttpClient(String requestUrl, String requestMethod, RequestBody body, Map<String, String> headers) {
        if(headers == null){
            headers = new HashMap<>();
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.MINUTES) // 连接超时时间
                .readTimeout(5, TimeUnit.MINUTES) // 读取超时时间
                .writeTimeout(5, TimeUnit.MINUTES) // 写入超时时间
                .build();
        Request request = new Request.Builder()
                .url(requestUrl)
                .method(requestMethod, body != null ? body : null)
                .headers(Headers.of(headers))
                .build();
        try (Response response = client.newCall(request).execute()) { // 使用 try-with-resources 确保自动关闭响应体
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                String errorMessage = response.header("X-Bce-Error-Message");
                String requestId = response.header("X-Bce-Request-Id");
                System.out.println("Request failed: " + response.code() + " - "
                        + response.message() + " - " + errorMessage + " - " + requestId);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送http请求
     * @param requestUrl
     * @return
     */
    public static String getFlightVideoApiSession(String requestUrl, String requestMethod, RequestBody body, Map<String, String> headers){
        if(headers == null){
            headers = new HashMap<>();
        }
        OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
                    .readTimeout(30, TimeUnit.SECONDS) // 读取超时时间
                    .writeTimeout(30, TimeUnit.SECONDS) // 写入超时时间
                    .build();
        Request request = new Request.Builder()
                .url(requestUrl)
                .method(requestMethod, body != null ? body : null)
                .headers(Headers.of(headers))
                .build();
        try (Response response = client.newCall(request).execute()) { // 使用 try-with-resources 确保自动关闭响应体
            if (response.isSuccessful()) {
                JSONObject bodyData = JSONObject.parseObject(response.body().string());
                if(bodyData.getIntValue("resultCode") != 0){
                    return null;
                }
                return response.header("Set-Cookie");
            } else {
                String errorMessage = response.header("X-Bce-Error-Message");
                String requestId = response.header("X-Bce-Request-Id");
                System.out.println("Request failed: " + response.code() + " - "
                        + response.message() + " - " + errorMessage + " - " + requestId);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

	public static Response sendOkHttpClientWithResponse(String url, String method, Map<String, String> headers, RequestBody body) throws IOException {
		OkHttpClient client = new OkHttpClient();
		Request.Builder builder = new Request.Builder().url(url);

		if ("GET".equalsIgnoreCase(method)) {
			builder.get();
		} else if ("POST".equalsIgnoreCase(method)) {
			builder.post(body != null ? body : RequestBody.create("", null));
		}

		if (headers != null) {
			headers.forEach(builder::addHeader);
		}

		Request request = builder.build();
		return client.newCall(request).execute();
	}

//    public OkHttpUtil() {
//        // 跳过证书验证
//        trustAllCertificates();
//    }
//
//    /**
//     * 信任所有证书
//     */
//    private void trustAllCertificates() {
//        try {
//            // 创建一个信任所有证书的TrustManager
//            TrustManager[] trustAllCerts = new TrustManager[] {
//                    new X509TrustManager() {
//                        public X509Certificate[] getAcceptedIssuers() {
//                            return null;
//                        }
//                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
//                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
//                    }
//            };
//
//            // 设置SSLContext为使用上述TrustManager
//            SSLContext sc = SSLContext.getInstance("TLS");
//            sc.init(null, trustAllCerts, new java.security.SecureRandom());
//            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//
//            // 创建一个HostName验证器，信任所有主机名
//            HostnameVerifier allHostsValid = (hostname, session) -> true;
//            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

}
